import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

public class TccPropertySourceSpringBoot2x extends BaseTccPropertySource {
    private final PropertySourceLoader loader;

    protected TccPropertySourceSpringBoot2x(TccPlusProperties.TccConfig tcc, PropertySourceLoader loader) {
        super(tcc.getPsm(), tcc.getConfigSpace(), tcc.getEnv(), tcc.getKey());
        this.loader = loader;
    }

    @Override
    protected Properties loadProperties(String config) throws IOException {
        List<PropertySource<?>> loaded = loader.load(getName(), new StringResource(config));
        Properties properties = new Properties();
        for (PropertySource<?> ps : loaded) {
            if (!(ps instanceof EnumerablePropertySource)) {
                continue;
            }
            for (String propertyName : ((EnumerablePropertySource<?>) ps).getPropertyNames()) {
                properties.put(propertyName, Objects.requireNonNull(ps.getProperty(propertyName)));
            }
        }
        return properties;
    }
}
